package com.sinvo.oa.controller;

import com.sinvo.oa.entity.model.system.SysRole;
import com.sinvo.oa.entity.model.system.SysUser;
import com.sinvo.oa.entity.vo.system.PwdVo;
import com.sinvo.oa.exception.CustomException;
import com.sinvo.oa.result.R;
import com.sinvo.oa.result.ResultCode;
import com.sinvo.oa.service.SysDeptService;
import com.sinvo.oa.service.SysPostService;
import com.sinvo.oa.service.SysRoleService;
import com.sinvo.oa.service.SysUserService;
import com.sinvo.oa.util.LoginUserInfoUtils;
import com.sinvo.oa.util.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.UUID;

/**
 * @Description 个人信息控制器
 */
@Api(tags = "个人信息管理接口")
@RestController
@RequestMapping("admin/system/sysProfile")
public class SysProfileController {

    public final static String UPLOAD_PATH_PREFIX = "service-oa/src/main/resources/avatar";

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysPostService sysPostService;

    @ApiOperation(value = "获取登录用户信息")
    @GetMapping("getProfile")
    public R getProfile(){
        //获取登录用户名
        String username = LoginUserInfoUtils.getUsername();
        //返回对象
        SysUser user = sysUserService.findUserByUserName(username);
        //根据id查询名 补全岗位部门字段
        String deptName = sysDeptService.getById(user.getDeptId()).getName();
        String postName = sysPostService.getById(user.getPostId()).getName();
        user.setDeptName(deptName);
        user.setPostName(postName);
        //补全角色字段
        List<SysRole> roleList = (List<SysRole>) sysRoleService.findRoleByUserId(user.getId()).get("assignedRoleList");
        user.setRoleList(roleList);
        return R.success(user);
    }

    @ApiOperation(value = "修改密码")
    @PutMapping("updatePwd")
    public R updatePwd(@RequestBody PwdVo pwdVo){
        //获取前端输入
        String oldPwd = pwdVo.getOldPwd();
        String newPwd = pwdVo.getNewPwd();
        String confirmPwd = pwdVo.getConfirmPwd();
        //当前用户对象
        SysUser user = sysUserService.getById(LoginUserInfoUtils.getUserId());
        //比对数据库密码
        if (!MD5.encrypt(oldPwd).equals(user.getPassword())){
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"密码错误");
        }
        if (!newPwd.equals(confirmPwd)){
            throw new CustomException(ResultCode.DATA_ERROR.getCode(),"两次密码输入不一致");
        }
        //进行更新
        user.setPassword(MD5.encrypt(newPwd));
        sysUserService.updateById(user);
        return R.success();
    }

    @PostMapping("updateAvatar")
    public R updateAvatar(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        //获取文件名后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //UUID生产文件名
        String fileName = UUID.randomUUID() + suffix;

        //创建目录对象
        File dir = new File(UPLOAD_PATH_PREFIX + File.separator);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，需要创建
            dir.mkdirs();
        }
        File destFile = new File(dir.getAbsolutePath() + File.separator + fileName);
        try {
            //将临时文件转存到指定位置
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取文件路径
        String avatarPath = destFile.getPath();
        //存放数据库
        SysUser user = sysUserService.getById(LoginUserInfoUtils.getUserId());
        user.setHeadUrl(avatarPath);
        sysUserService.updateById(user);
        return R.success();
    }

}
